package utils

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"

	"github.com/spf13/viper"
)

type SubscribeMessageData struct {
	Value any `json:"value"`
}
type PostData struct {
	TemplateId       string                          `json:"template_id"`
	Page             string                          `json:"page"`
	Touser           string                          `json:"touser"`
	Data             map[string]SubscribeMessageData `json:"data"`
	MiniprogramState string                          `json:"miniprogram_state"`
	Lang             string                          `json:"lang"`
}

// 执行消息通知
func SendWxMessage(orderId uint, price float32, senderName string, openId string) {
	fmt.Println("开始执行微信消息通知")
	//1.先获取access_token
	appid := viper.GetString("wxtoken.appId")
	fmt.Println("appid:", appid)
	secret := viper.GetString("wxtoken.wxSecret")
	targetUrl := fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", appid, secret)
	resp, err := http.Get(targetUrl)
	if err != nil {
		log.Fatalf("请求失败：%v", err)
	}
	defer resp.Body.Close()
	// 检查HTTP响应状态码
	if resp.StatusCode != http.StatusOK {
		log.Fatalf("请求失败，状态码: %d", resp.StatusCode)
	}
	// 读取响应体
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatalf("读取响应体失败: %v", err)
	}
	jsonData := []byte(body)
	var res map[string]interface{}
	json.Unmarshal(jsonData, &res)
	// 检查errcode属性是否存在
	if err, ok := res["errcode"]; ok {
		fmt.Println("属性 'errcode' 存在，转换json失败", err, res)
		return
	}
	access_token := res["access_token"].(string)
	fmt.Println("成功获取到access_token：", access_token)

	//2.发送消息
	sendMessageBaseUrl := fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=%s", access_token)
	//组装携带参数

	messageData := make(map[string]SubscribeMessageData)
	messageData["character_string1"] = SubscribeMessageData{Value: fmt.Sprint(orderId)}
	messageData["thing13"] = SubscribeMessageData{Value: senderName}
	messageData["time14"] = SubscribeMessageData{Value: GetFormatNowTime()}
	requestBody := PostData{
		TemplateId:       "0YQcLjTSVzOOf4SvUjT-v2FoO8c2J91W2qb1mhdPF-8",
		Page:             "subpages/order/classOrder?status=2",
		Touser:           openId,
		Data:             messageData,
		MiniprogramState: "formal",
		Lang:             "zh_CN",
	}
	// 将数据编码为JSON格式的请求体
	requestBodyJson, err := json.Marshal(requestBody)
	if err != nil {
		log.Fatalf("编码JSON失败: %v", err)
	}
	// 创建请求对象
	req, err := http.NewRequest("POST", sendMessageBaseUrl, bytes.NewBuffer(requestBodyJson))
	if err != nil {
		log.Fatalf("创建请求失败: %v", err)
	}
	// 发送请求
	client := &http.Client{}
	respMs, err := client.Do(req)
	if err != nil {
		log.Fatalf("发送通知的请求失败: %v", err)
		return
	}
	defer respMs.Body.Close()

	// 解析JSON响应
	var response map[string]interface{}
	all, _ := io.ReadAll(respMs.Body)
	json.Unmarshal(all, &response)

	if int(response["errcode"].(float64)) != 0 {
		log.Printf("errcode: %v, errmsg: %v", response["errcode"], response["errmsg"])
		return
	}
	fmt.Println("成功发送微信通知")
}
